﻿using Amazon;
using Amazon.S3;
using Amazon.S3.Transfer;
using Microsoft.AspNetCore.Http;
using TradeDataAPI.Core.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TradeDataAPI.Core.Common
{
    public class ImagesHelper
    {
        /// <summary>
        /// 将Base64字符串转换为IFormFile
        /// </summary>
        /// <param name="base64String"></param>
        /// <returns></returns>
        public static IFormFile ConvertBase64ToIFormFile(string base64String)
        {
            // 移除Base64字符串的前缀
            var base64Data = base64String.Split(',')[1];

            string fileName = Guid.NewGuid().ToString() + ".jpg";
            // 解码Base64字符串
            byte[] bytes = Convert.FromBase64String(base64Data);

            // 创建MemoryStream
            var stream = new MemoryStream(bytes);

            // 创建FormFile
            IFormFile file = new FormFile(stream, 0, stream.Length, "file", fileName)
            {
                Headers = new HeaderDictionary(),
                ContentType = "image/jpeg" // 根据实际情况设置ContentType
            };

            return file;
        }




        /// <summary>
        /// 上传图片到S3
        /// </summary>
        /// <param name="bucket"></param>
        /// <param name="key"></param>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static async Task<string> UploadFileToS3(string bucket, string key, Stream stream)
        {
            AmazonS3Client s3Client = new AmazonS3Client(
                AppSetting.GetSection("S3Setting")["AccessKeyiId"],
                AppSetting.GetSection("S3Setting")["SecretAccessKey"],
                RegionEndpoint.GetBySystemName(AppSetting.GetSection("S3Setting")["Region"]));
            await new TransferUtility(s3Client).UploadAsync(stream, bucket, key);
            return $"{AppSetting.GetSection("S3Setting")["VisitBaseUrl"]}{key}";
        }










    }
}
